package com.imedia.frame.lucene.service.impl;

import java.io.IOException;

import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;

import com.imedia.frame.lucene.service.AbstractSearchService;
import com.imedia.frame.lucene.service.ISearchService;

/**
 * <p>Title: 全站检索</p>
 * <p>Description: lucene检索模块类</p>
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: </p>
 * @author qiuy
 * @version 1.0
 */
public  class SearchServiceImpl extends AbstractSearchService implements ISearchService{
	
	/**
	 * <p>Description: 初始化searcher 默认的用mmanalyzer</p>
	 */
	public  void initSearcher(){
		initMMAnalyzerIndexSearcher();
	}
	/**
	 * <p>Description: 创建query</p>
	 * @param queryString
	 */
	public void createQuery(String queryString){
		try {
			
			query = queryParser.parse(queryString);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	/**
	 * <p>Description: 普通执行查询</p>
	 * @param queryString 查询语句
	 * @return
	 */
	public Hits executeQuery(String queryString){
		this.createQuery(queryString);
		Hits hits = null;
		try {
			
			hits = searcher.search(query);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hits;
	}
	/**
	 * <p>Description: 结果排序查询</p>
	 * @param queryString  查询语句
	 * @param sortProperty 排序字段
	 * @param propertyType 排序字段的类型
	 * @param flag true为降序 false为升序
	 * @return
	 */
	public Hits executeQueryBySort(String queryString,String sortProperty,String propertyType,boolean flag){
		this.createQuery(queryString);
		Hits hits = null;
		SortField sortField = null;
		if (propertyType != null && "string".equalsIgnoreCase(propertyType)) {
			
			sortField = new SortField(sortProperty,SortField.STRING,flag);
			
		}else if (propertyType != null && "int".equalsIgnoreCase(propertyType)) {
			
			sortField = new SortField(sortProperty,SortField.INT,flag);
			
		}else{
			
			sortField = new SortField(sortProperty,SortField.AUTO,flag);
			
		}
		Sort sort = new Sort(sortField); 
		try {
			hits = searcher.search(query, sort);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hits;
	}
}
